﻿/*
 * Author:xmfdsh 11届网络部--邓世豪
 * DataTime：2014-6-9
 * Copyright © 2014 大学生勤工助学服务队 Powered by xmfdsh & 四小狼工作室.
 * 版权所有，违者必究
 */
using QGZX.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace QGZX.Logic.OA
{
    public class ServiceController : Controller
    {
        //------------------------------------------------排班系统-------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        public ActionResult schedulingSystem()
        {
            return View();
        }
        #region 自定义排班系统功能页面 + SelfScheduling()
        /// <summary>
        /// 自定义排班系统功能页面
        /// </summary>
        /// <returns></returns>
        public ActionResult SelfScheduling()
        {
            MODEL.qgzx_config model = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName != null).FirstOrDefault();
            ViewBag.configModel = model;
            return View();
        } 
        #endregion

        #region Action操作方法集合 + Action()
        /// <summary>
        /// Action操作方法集合
        /// </summary>
        /// <returns></returns>
        public ActionResult Action()
        {
            string dowhat = Request.Form["dowhat"];
            if (dowhat == null)
                dowhat = Request.QueryString["dowhat"];
            if (dowhat.Equals("Setting"))
            {
                //自定义排班系统的设置
                string name = "";
                string num = Request.Form["num"];
                for (int i = 0; i < Convert.ToInt32(num); i++)
                {
                    string important = Request.Form["important" + i];
                    name += important + ",";
                }
                MODEL.qgzx_config config = new MODEL.qgzx_config();
                config = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName == "系统设置").FirstOrDefault();
                config.Help = num;
                config.Remark = name;
                OperateContext.Current.BLLSession.Iqgzx_configBLL.ModifyBy(config, x => x.SystemName == "系统设置", "Help", "Remark");
                return OperateContext.Current.RedirectAjax("ok", "操作成功", null, "");
            }
            return null;
        } 
        #endregion

        #region 关闭排班收集系统 + ActionResult Close()
        /// <summary>
        /// 关闭排班收集系统
        /// </summary>
        /// <returns></returns>
        public ActionResult Close()
        {
            MODEL.qgzx_config config = new MODEL.qgzx_config();
            config = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName == "系统设置").FirstOrDefault();
            config.Version = "0";
            OperateContext.Current.BLLSession.Iqgzx_configBLL.ModifyBy(config, x => x.SystemName == "系统设置", "Version");
            return OperateContext.Current.RedirectAjax("ok", "操作成功", null, "");
        } 
        #endregion

        #region 查看默认模式排班系统收集到的结果 + ActionResult GetSelfClass()
        /// <summary>
        /// 查看默认模式排班系统收集到的结果
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSelfClass()
        {
            List<MODEL.qgoa_user> list_user;
            List<MODEL.qgoa_department> list_department2 = OperateContext.Current.BLLSession.Iqgoa_departmentBLL.GetListBy(x => x.Id != null);
            for (int i = 0; i < list_department2.Count; i++)
            {
                int test = list_department2[i].Id;
                list_user = OperateContext.Current.BLLSession.Iqgoa_userBLL.GetListBy(x => x.DepartmentId == test).ToList();
                //GetJson 函数传入想收集的部门模型，可返回部门json字符串（如传入所有网络部的实体类，返回部门json）
                //然后update 存储到部门里面去，方便读取。
                list_department2[i].Remark = QGZX.Helper.GetSelfClass.GetJson(list_user);
                OperateContext.Current.BLLSession.Iqgoa_departmentBLL.ModifyBy(list_department2[i], x => x.Id == test, "Remark");
                //departmentBLL.UpdateDepartment(list_department[i].Id.ToString(), list_department[i].Name, QGZX.Helper.GetSelfClass.GetJson(list_user));
            }
            //-----------------------------------直接从原先OA移植过来，分两步走-----------------------------------------
            MODEL.qgzx_config config = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName == "系统设置").FirstOrDefault();
            int num = Convert.ToInt32(config.Help);
            string[] Remark = config.Remark.Split(',');

            List<MODEL.qgoa_department> list_department = OperateContext.Current.BLLSession.Iqgoa_departmentBLL.GetListBy(x => x.Id != null);
            MODEL.SelfClass a = new MODEL.SelfClass();
            List<MODEL.SelfClass> temp = new List<MODEL.SelfClass>();

            for (int i = 0; i < list_department.Count; i++)
            {
                MODEL.SelfClass b = new MODEL.SelfClass();
                //判断部门json里面是否为空
                if (list_department[i].Remark.ToString().Length < 20)
                    continue;
                b = (MODEL.SelfClass)JsonToObject(list_department[i].Remark.ToString(), a);
                temp.Add(b);
            }
            MODEL.qgzx_config model = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName != null).FirstOrDefault();
            ViewBag.configModel = model;
            ViewBag.resultList = temp;
            ViewBag.Remark = Remark;
            ViewBag.list_department = list_department;
            return View();
        } 
        #endregion

        #region 把json字符串转化为object类型 + JsonToObject(string jsonString, object obj)
        /// <summary>
        /// 把json字符串转化为object类型
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object JsonToObject(string jsonString, object obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            return serializer.ReadObject(mStream);
        } 
        #endregion

        #region 根据华农宝实现收集课表的查看收集情况功能 + GetCollectClass()
        /// <summary>
        /// 根据华农宝实现收集课表的查看收集情况功能
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCollectClass()
        {
            List<MODEL.qgoa_user> list_user;
            List<MODEL.qgoa_department> list_department2 = OperateContext.Current.BLLSession.Iqgoa_departmentBLL.GetListBy(x => x.Id != null);
            for (int i = 0; i < list_department2.Count; i++)
            {
                int test = list_department2[i].Id;
                list_user = OperateContext.Current.BLLSession.Iqgoa_userBLL.GetListBy(x => x.DepartmentId == test).ToList();
                //GetJson 函数传入想收集的部门模型，可返回部门json字符串（如传入所有网络部的实体类，返回部门json）
                //然后update 存储到部门里面去，方便读取。
                list_department2[i].Remark = QGZX.Helper.GetCollectJson.GetJson(list_user);
                OperateContext.Current.BLLSession.Iqgoa_departmentBLL.ModifyBy(list_department2[i], x => x.Id == test, "Remark");
                //departmentBLL.UpdateDepartment(list_department[i].Id.ToString(), list_department[i].Name, QGZX.Helper.GetSelfClass.GetJson(list_user));
            }
            //-----------------------------------直接从原先OA移植过来，分两步走-----------------------------------------
            MODEL.qgzx_config config = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName == "系统设置").FirstOrDefault();
            int num = Convert.ToInt32(config.Help);
            string[] Remark = config.Remark.Split(',');

            List<MODEL.qgoa_department> list_department = OperateContext.Current.BLLSession.Iqgoa_departmentBLL.GetListBy(x => x.Id != null);
            GetCollectJson.department a = new GetCollectJson.department();
            List<GetCollectJson.department> temp = new List<GetCollectJson.department>();

            for (int i = 0; i < list_department.Count; i++)
            {
                GetCollectJson.department b = new GetCollectJson.department();
                //判断部门json里面是否为空
                if (list_department[i].Remark.ToString().Length < 20)
                    continue;
                b = (GetCollectJson.department)JsonToObject(list_department[i].Remark.ToString(), a);
                temp.Add(b);
            }
            MODEL.qgzx_config model = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName != null).FirstOrDefault();
            ViewBag.configModel = model;
            ViewBag.resultList = temp;
            ViewBag.Remark = Remark;
            ViewBag.list_department = list_department;
            return View();
        } 
        #endregion

        #region 根据华农宝接口实现的自动收集课表 + ActionResult Collect()
        /// <summary>
        /// 根据华农宝接口实现的自动收集课表
        /// </summary>
        /// <returns></returns>
        public ActionResult Collect()
        {
            string error = "";
            string nothing = "";
            int times = 0;
            int success = 0;
            int defeat = 0;
            //获取所有人 到list中去
            List<MODEL.qgoa_user> list = OperateContext.Current.BLLSession.Iqgoa_userBLL.GetListBy(x => x.Id != null);
            //循环去获取所有人课表
            for (int i = 0; i < list.Count; i++)
            {
                string identify = "";
                if (true)
                {
                    //第一个操作，登陆。（后面再添加出错判断）
                    string[] test;
                    //判断密码是否为空
                    if (list[i].RealPassword.Equals(""))
                    {
                        nothing += list[i].Name + ",";
                        continue;
                    }
                    string login = QGZX.Helper.Collect.GetJsonClass("http://myiscau.duapp.com/wp/jwxt/login.php", "nu=" + list[i].Number + "&p=" + list[i].RealPassword + "&ta=4");
                    test = Regex.Split(login, "\\&\\*", RegexOptions.IgnoreCase);
                    //判断该入口是否崩溃
                    if (test[0].Trim().Equals("41"))
                    {
                        if (times < 15)
                        {
                            times++; i--;
                            continue;
                        }
                        else
                        {
                            times = 0;
                            defeat++;
                            continue;
                        }
                    }
                    //密码错误
                    if (test[0].Trim().Equals("0"))
                    {
                        error += list[i].Name + ",";
                        continue;
                    }
                    //为标记属性赋值
                    identify = test[0].Trim();
                    //第二个操作，读取课表
                    string myClass = QGZX.Helper.Collect.GetJsonClass("http://myiscau.duapp.com/wp/jwxt/kcb.php", "nu=" + list[i].Number + "&na=" + test[1].Trim().ToString() + "&ta=4&c=" + identify + "&ty=0");
                    //判断入口是否崩溃
                    if (myClass.Trim().Equals("41"))
                    {
                        if (times < 15)
                        {
                            times++; i--;
                            continue;
                        }
                        else
                        {
                            times = 0;
                            defeat++;
                            continue;
                        }
                    }
                    success++;
                    int tempId = Convert.ToInt32(list[i].Id);
                    MODEL.qgoa_user temp = OperateContext.Current.BLLSession.Iqgoa_userBLL.GetListBy(x => x.Id == tempId).FirstOrDefault();
                    temp.Json = myClass;
                    OperateContext.Current.BLLSession.Iqgoa_userBLL.ModifyBy(temp, x => x.Id == tempId, "Json");
                }
            }
            return OperateContext.Current.RedirectAjax("ok", "一共：" + list.Count + "个</br>成功了：" + success + "个</br>密码错误：" + error + "个</br>" + "没填密码：" + nothing + "个</br>接入点奔溃：" + defeat + "个", null, null);
        } 
        #endregion

        #region 华农宝式排班系统功能页面 + CollectScheduling()
        /// <summary>
        /// 华农宝式排班系统功能页面
        /// </summary>
        /// <returns></returns>
        public ActionResult CollectScheduling()
        {
            MODEL.qgzx_config model = OperateContext.Current.BLLSession.Iqgzx_configBLL.GetListBy(x => x.SystemName != null).FirstOrDefault();
            ViewBag.configModel = model;
            return View();
        }
        #endregion
    }
}
